package com.muki.jms;

import java.io.Serializable;

import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.log4j.Logger;

public class JmsSender {

	private Logger log = Logger.getLogger(JmsSender.class);
	private JmsPreparedConnection prepared = null;
	private MessageProducer producer;
	private Session session = null;

	public JmsSender() {
		prepared = new JmsPreparedConnection();
	}

	public void bindQueue(String queue) throws JMSException {
		//如果producer为空，则绑定queue
		if(session==null) {
			session = prepared.init();
		}
		Queue que = session.createQueue(queue);
		if(que!=null) {
			producer = session.createProducer(que);
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		} else
			log.debug("the que "+queue+" creating failed");
	}	

	public void bindTopic(String topic) throws JMSException {
		if(producer==null) {
			session = prepared.init();
		}
		Topic top = session.createTopic(topic);
		if(top!=null) {
			producer = session.createProducer(top);
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		} else
			log.debug("the topic "+topic+" creating error!");
	}

	public MessageProducer getProducer() {
		return producer;
	}

	/* 
	 * 发送文本消息 
	 */  
	public void sendTextMsg(boolean istopic,String MsgContent,String name) throws JMSException{  
		if(istopic)
			bindTopic(name);
		else
			bindQueue(name);
		if(session==null)
			session = prepared.init();
		Message msg = session.createTextMessage(MsgContent);
		producer.send(msg);
	}  
	/* 
	 * 发送MAP类型消息 
	 */  
	public void sendMap(boolean istopic,MapMessage map,String name) throws JMSException{  
		if(istopic)
			bindTopic(name);
		else
			bindQueue(name);
		producer.send(map);
		session.commit();
	}  
	/* 
	 * 发送Object类型消息 
	 */  
	public void sendObj(boolean istopic,Object obj,String name) throws JMSException{  
		if(istopic)
			bindTopic(name);
		else
			bindQueue(name);
		if(session==null)
			session = prepared.init();
		ObjectMessage objMsg=session.createObjectMessage((Serializable) obj);//发送对象时必须让该对象实现serializable接口  
		producer.send(objMsg);  
		session.commit();
	}  
	
	public void closeConnection() throws JMSException {
		prepared.close();
	}

}  
